<template>
  <div class="flex flex-col h-full">
    <SearchContainer is-width @search="getData" @reset="onReset">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '78px' } }">
        <a-form-item name="pyjm" class="!w-72">
          <a-input v-model:value="formState.pyjm" placeholder="姓名/助记码/手机号/卡号/身份证号" />
        </a-form-item>
        <a-form-item name="brBlkh" :label="isBJMSG ? '病案号' : '病历号'" class="!w-64">
          <a-input v-model:value="formState.brBlkh" :placeholder="isBJMSG ? '请输入病案号' : '请输入病历号'" />
        </a-form-item>
        <a-form-item name="dateRange" label="创建日期" class="!w-[300px] ml-3">
          <a-range-picker v-model:value="formState.dateRange" arrow-point-at-center allow-clear format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item v-if="!isArmy" label="关注项目" class="!w-64 mx-3">
          <SelectFocusProject v-model:value="formState.brGzxm" max-tag-count="responsive" />
        </a-form-item>
        <a-form-item v-if="!isArmy" label="客户来源" class="!w-64">
          <SelectCustomerSource v-model:value="formState.khly" multiple max-tag-count="responsive" />
        </a-form-item>
        <a-form-item v-if="!isArmy" label="业务员" class="!w-64 ml-2">
          <SelectTable v-model:value="formState.brYwyName" type="员工" page-size="999" @blur="onBlur('brYwy')" @select="onSelectEmployee('brYwy', $event)" />
        </a-form-item>
        <a-form-item v-if="!isArmy" label="负责人" class="!w-64 ml-2">
          <SelectTable v-model:value="formState.brFzrName" type="员工" page-size="999" @blur="onBlur('brFzr')" @select="onSelectEmployee('brFzr', $event)" />
        </a-form-item>
        <a-form-item v-if="!isArmy" label="咨询师" class="!w-64 ml-2">
          <SelectTable
            v-model:value="formState.brZxsName"
            type="员工"
            page-size="999"
            :search-params="{ emplbid: '14' }"
            @blur="onBlur('brZxs')"
            @select="onSelectEmployee('brZxs', $event)"
          />
        </a-form-item>
        <a-form-item v-if="!isArmy" label="客户标签" class="!w-64 ml-2">
          <!-- mode="multiple" -->
          <a-select
            v-model:value="formState.patientLabel"
            :options="tagsList"
            allow-clear
            :max-tag-count="2"
            :field-names="{ label: 'labelName', value: 'id' }"
            placeholder="请选择"
            @change="onSelectLabel"
          />
        </a-form-item>
        <a-form-item v-if="!isArmy" class="!w-64 ml-2">
          <a-select
            v-model:value="formState.patientLabelList"
            :options="tagsListAll"
            allow-clear
            mode="multiple"
            :max-tag-count="2"
            :field-names="{ label: 'itemName', value: 'id' }"
            placeholder="请选择"
          />
        </a-form-item>
        <a-form-item v-if="isBJMSG" name="bah" label="病历号" class="!w-64">
          <a-input v-model:value="formState.bah" placeholder="请输入病历号" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2 flex-1">
      <a-button type="primary" class="mb-2 mr-2" @click="onClickAdd()">建档</a-button>
      <BaseExport
        type="门诊"
        name="患者档案"
        code="00001135"
        :search-params="{ ...formState, createTimeStdate: formState.dateRange?.[0], createTimeEddate: formState.dateRange?.[1] }"
      >
        导出
      </BaseExport>
      <!-- :column-code="getSystemConfig('IS_HIS_CONNECTIVITY_PATIENT') ? '000767' : '00001135'" -->
      <BaseTable
        :loading="loading"
        :column-code="getSystemConfig('IS_HIS_CONNECTIVITY_PATIENT') === '1' ? '000767' : '00001135'"
        fill
        :scroll="{ x: 2950 }"
        :data-source="tableData"
        bordered
        :pagination="pagination"
        :exclude-columns="getSystemConfig('ENABLE_CHARGE_STANDARD_MODE') === '1' ? [] : ['chargeStdName']"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex == 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex == 'brName'">
            <PatientPopoverCard :patient-info="record" @change="onChange">
              <div class="cursor-pointer text-primary hover:underline">
                {{ record?.brName || '姓名' }}
              </div>
            </PatientPopoverCard>
          </template>
          <template v-if="column.dataIndex == 'brAge'">
            <span v-if="record.brAge === '0' || record.brAge === 0 || record.brAge === '0岁'">-</span>
            <span v-else>{{ record.brAge }}</span>
          </template>
          <template v-if="column.dataIndex == 'brYwyName'">
            {{ record.brYwyName || record.brYwy }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button v-authority type="link" size="small" @click="onClickAdd(record)"> 修改 </a-button>
            <a-button v-if="!isArmy" type="link" size="small" @click="onPrint(record)"> 客户标签 </a-button>
            <a-button type="link" size="small" @click="onClickRegister(record)"> {{ isArmy ? '登记' : '挂号' }} </a-button>
            <TableMoreButton>
              <a-button v-if="!isArmy" type="link" size="small" @click="onClickDeposit(record)"> 收取押金 </a-button>
            </TableMoreButton>
          </template>
        </template>
      </BaseTable>
    </a-card>
    <!-- 普通样式 -->
    <PatientFiles v-model:open="editOpen" :row-data="rowData" is-save @success="onSuccess" />
    <!-- 医保样式 -->
    <PatientFilesDefend v-model:open="editOpenDefend" :row-data="rowData" is-save @success="onSuccess" />
    <RegisterModal v-model:open="registerOpen" :row-data="rowData" title="挂号" @success="onSuccess" />
  </div>
</template>
<script setup>
import { message } from 'ant-design-vue'
// import dayjs from 'dayjs'
import { getSystemConfig } from '@/utils/systemConfig'
import PatientFiles from '@/components/PatientFiles'
import PatientFilesDefend from '@/components/PatientFilesDefend'
import RegisterModal from '@/components/RegisterModal'
import PatientPopoverCard from '@/components/business/PatientPopoverCard'
import useStore from '../../store'

const store = useStore()

const route = useRoute()
const router = useRouter()
const rowData = ref({})
const tagsList = ref([])
const tagsListMany = ref([])
const tagsListAll = ref([])
const editOpen = ref(false)
const editOpenDefend = ref(false)
const registerOpen = ref(false)
const formRef = ref(null)
const isMedical = ref()
const formState = ref({
  brId: '',
  brMob: '',
  brName: '',
  brSfz: '',
  pyjm: '',
  ofAll: 1,
  khly: [],
  dateRange: []
})

const onBlur = (key) => {
  formState.value[key] = ''
}

const onSelectEmployee = (key, select) => {
  formState.value[key + 'Name'] = select.empName
  formState.value[key] = select.empId
}

const onClickAdd = (row = {}) => {
  rowData.value = { ...row }
  if (isMedical.value) {
    editOpenDefend.value = true
  } else {
    editOpen.value = true
  }
}
const onClickRegister = (row) => {
  if (getSystemConfig('GHDJYS') === '1') {
    rowData.value = { ...row }
    registerOpen.value = true
  } else {
    router.push({
      path: '/out-registration/register',
      query: {
        id: row.brId,
        status: '3'
      }
    })
    store.patientInfo = { ...row }
  }
}
const { loading, tableData, pagination, getData } = useTable({
  url: '/outp/mzdj/getPatientInfoList',
  params: formState.value,
  immediate: true,
  formatParams: (params) => {
    return {
      ...params,
      createTimeStdate: params.dateRange?.[0],
      createTimeEddate: params.dateRange?.[1]
    }
  }
})

const onClickDeposit = (row) => {
  store.patientInfo = { ...row }
  router.push({
    path: '/out-registration/deposit',
    query: {
      status: 1
    }
  })
}

// 打印
const onPrint = async (row) => {
  const { code, msg, data } = await post('/outp/outPrint/getMedicalRecordLabelPrint', { brId: row.brId, oprLsh: row.lsh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

//获取患者信息
const getPatientInfo = async () => {
  if (route.query?.id) {
    const { code, data } = await get('/common/patient/getPatientInfo?br_id=' + route.query.id)
    if (code !== 0) return
    rowData.value = { ...data }
    formState.value.jksy = 2
    editOpen.value = true
  }
}

// 客户标签
const getTagsList = async () => {
  const { code, data, msg } = await post('/operation/opex/getAllTagsItem', { status: 0 })
  if (code !== 0) return message.error(msg || '获取标签失败')
  tagsList.value = data.map((item) => {
    return {
      labelName: item.labelName,
      id: item.id
    }
  })
  const arr = data
    .map((item) => {
      if (item.children.length > 0) {
        return item.children.map((j) => {
          return {
            id: j.id,
            itemName: j.itemName,
            labelId: j.labelId
          }
        })
      }
    })
    .flat()
  tagsListMany.value = arr.filter((item) => item !== undefined)
}

// 选中客户标签
const onSelectLabel = (id) => {
  formState.value.patientLabelList = []
  const arrAll = tagsListMany.value.map((item) => {
    if (item.labelId === id) {
      return {
        id: item.id,
        itemName: item.itemName
      }
    } else {
      return
    }
  })
  tagsListAll.value = arrAll.filter((item) => item !== undefined)
}

const onReset = () => {
  formRef.value.resetFields()
  formState.value.brGzxm = []
  formState.value.khly = []
}

const onSuccess = () => {
  rowData.value = {}
  getData()
}
const isArmy = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统
const isBJMSG = getSystemConfig('GHDJYS') === '4' //是否北京茗视光
onMounted(async () => {
  if (route.query?.id) {
    formState.value.pyjm = route.query.id
    getPatientInfo()
  }
  isMedical.value = getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '1' //是否启用医保
  getTagsList()
})
</script>
